package com.hxrfid.sms.util;

import com.hxrfid.common.context.SecurityContextHolder;
import com.hxrfid.common.exception.ServiceException;
import com.hxrfid.common.utils.Assert;
import com.hxrfid.common.utils.DateUtils;
import com.hxrfid.common.utils.JsonUtils;
import com.hxrfid.common.utils.spring.SpringUtils;
import com.hxrfid.sms.core.SmsTemplate;
import com.hxrfid.sms.domain.bo.SysSmsRecordBo;
import com.hxrfid.sms.entity.SmsResult;
import com.hxrfid.sms.exception.SmsException;
import com.hxrfid.sms.service.ISysSmsConfigService;
import com.hxrfid.sms.service.ISysSmsRecordService;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Objects;

/**
 * 短信工具类
 *
 * @author lsh
 */
@Slf4j
public class SmsUtil {

    /**
     * 发送短信
     * @param phones     电话号(多个逗号分割)
     * @param templateId 模板id
     * @param param      模板对应参数
     */
    public static SmsResult send(String phones, String templateId, Map<String, String> param) throws ServiceException {
        SysSmsRecordBo bo = new SysSmsRecordBo();
        Assert.notBlank(phones, "手机号码不能为空");
        Assert.notBlank(templateId, "模板ID不能为空");
        ISysSmsConfigService sysSmsConfigService = SpringUtils.getBean(ISysSmsConfigService.class);
        ISysSmsRecordService sysSmsRecordService = SpringUtils.getBean(ISysSmsRecordService.class);
        try {
            bo.setPhoneNumber(phones);
            bo.setTemplateId(templateId);
            bo.setTenantId(SecurityContextHolder.getTenantId());
            bo.setContent(JsonUtils.toJsonString(param));
            bo.setSendTime(DateUtils.getNowDate());
            bo.setSuccessStatus("0");
            SmsTemplate smsTemplate = sysSmsConfigService.buildTemplate(templateId);
            bo.setConfigId(smsTemplate.getConfigId());
            Long id = sysSmsRecordService.insertByBo(bo);
            bo.setId(id);
            SmsResult smsResult = smsTemplate.send(phones, param);
            if (!smsResult.getIsSuccess()) {
                log.error("短信发送异常：{}", smsResult);
                bo.setFailReason(smsResult.getMessage());
            } else {
                bo.setSuccessStatus("1");
            }
            bo.setRemark(smsResult.getResponse());
            sysSmsRecordService.updateByBo(bo);
            return smsResult;
        } catch (SmsException e) {
            log.error("发送短信sms异常：" + e.getMessage(), e);
            if (Objects.nonNull(bo.getId())) {
                bo.setFailReason(e.getMessage());
                sysSmsRecordService.updateByBo(bo);
            }
            throw e;
        }
    }

}
